package com.ljy.utyun.swagger;

import java.io.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public abstract class SwaggerProcessor {

    public abstract boolean checkCanProcess(File file);

    public final void process(File file) throws IOException{
        if(!checkCanProcess(file)){
            return;
        }
        List<String> valueList= getFileValueList(file);

        doProcess(file,valueList);

        newFile(file,valueList);
    }


    public abstract List<String> doProcess(File file,List<String> valueList);

    public List<String> getFileValueList(File file) throws IOException {
        BufferedReader br=new BufferedReader(new FileReader(file));
        List<String> valueList=new LinkedList<>();
        String line;
        while((line=br.readLine())!=null){
            valueList.add(line);
        }
        br.close();
        return valueList;
    }

    public void newFile(File file,List<String> valueList) throws IOException {
        StringBuilder sb=new StringBuilder();
        valueList.stream().forEach(l->sb.append(l+"\n"));
        String path=file.getAbsolutePath();
        file.delete();
        file=new File(path);
        FileWriter writer=new FileWriter(file);
        writer.write(sb.toString());
        writer.close();
    }

    //获取第一个注解索引
    public int getAddLineIndex(List<String> valueList,int index){
        index--;
        while(valueList.get(index).trim().startsWith("@")){
            index--;
        }
        index++;
        return index;
    }
}
